package com.ywk.miaohsa.controller;

import com.ywk.miaohsa.domain.MiaoshaUser;
import com.ywk.miaohsa.redis.RedisService;
import com.ywk.miaohsa.result.Result;
import com.ywk.miaohsa.service.GoodsService;
import com.ywk.miaohsa.vo.GoodsDetailVo;
import com.ywk.miaohsa.vo.GoodsVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    @Autowired
    RedisService redisService;

    @RequestMapping("/to_list")
    @ResponseBody
    public Result<List<GoodsVo>> toList(Model model){
        List<GoodsVo> goodsList = goodsService.getGoodsList();
        model.addAttribute("goodsList", goodsList);
        return Result.success(goodsList);
//    	 return "goods_list";

    }

    @GetMapping("/detail")
    @ResponseBody
    public Result<GoodsDetailVo> detail(MiaoshaUser user, @RequestParam("goodsId") long goodsId){
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        long startAt = goods.getStartDate().getTime();
        long endAt = goods.getEndDate().getTime();
        long now = System.currentTimeMillis();
        int miaoshaStatus = 0;
        int remainSeconds = 0;
        if(now < startAt ) {//秒杀还没开始，倒计时
            miaoshaStatus = 0;
            remainSeconds = (int)((startAt - now )/1000);
        }else  if(now > endAt){//秒杀已经结束
            miaoshaStatus = 2;
            remainSeconds = -1;
        }else {//秒杀进行中
            miaoshaStatus = 1;
            remainSeconds = 0;
        }
        GoodsDetailVo vo = new GoodsDetailVo();
        vo.setGoods(goods);
        vo.setUser(user);
        vo.setRemainSeconds(remainSeconds);
        vo.setMiaoshaStatus(miaoshaStatus);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        vo.setStartTime(sdf.format(goods.getStartDate()));
        return Result.success(vo);
    }
}
